<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务内容" prop="serviceContent">
        <el-input
          v-model="queryParams.serviceContent"
          placeholder="请输入服务内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['order:orders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:orders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:orders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="orderId" width="80" />
      <el-table-column label="订单号" align="center" prop="orderNumber" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="服务内容" align="center" prop="serviceContent" :show-overflow-tooltip="true" />
      <el-table-column label="服务价格" align="center" prop="servicePrice" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="statusTagType(scope.row.status)">{{ statusFormat(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['order:orders:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:orders:edit']"
          >修改</el-button>
          <el-dropdown size="mini" @command="(command) => handleMoreActions(command, scope.row)">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="complete" v-if="scope.row.status === '待确定' || scope.row.status === '进行中'">标记完成</el-dropdown-item>
              <el-dropdown-item command="cancel" v-if="scope.row.status === '待确定'">取消订单</el-dropdown-item>
              <el-dropdown-item command="delete" v-hasPermi="['order:orders:remove']">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入订单号" :disabled="title.indexOf('修改') !== -1" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="服务内容" prop="serviceContent">
          <el-input v-model="form.serviceContent" type="textarea" placeholder="请输入服务内容" />
        </el-form-item>
        <el-form-item label="服务价格" prop="servicePrice">
          <el-input-number v-model="form.servicePrice" :precision="2" :step="10" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="viewDialogVisible" width="600px" append-to-body>
      <el-descriptions border :column="1" direction="vertical">
        <el-descriptions-item label="订单ID">{{ viewForm.orderId }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ viewForm.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ viewForm.customerName }}</el-descriptions-item>
        <el-descriptions-item label="服务内容">{{ viewForm.serviceContent }}</el-descriptions-item>
        <el-descriptions-item label="服务价格">{{ viewForm.servicePrice }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="statusTagType(viewForm.status)">{{ statusFormat(viewForm.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewForm.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(viewForm.updatedAt) }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/company/orders";

export default {
  name: "Orders",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单管理表格数据
      ordersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看弹出层
      viewDialogVisible: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [
        { value: "待确定", label: "待确定" },
        { value: "进行中", label: "进行中" },
        { value: "待评价", label: "待评价" },
        { value: "已完成", label: "已完成" },
        { value: "退款/售后", label: "退款/售后" }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        customerName: null,
        serviceContent: null,
        status: null
      },
      // 表单参数
      form: {},
      // 查看表单
      viewForm: {},
      // 表单校验
      rules: {
        orderNumber: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        serviceContent: [
          { required: true, message: "服务内容不能为空", trigger: "blur" }
        ],
        servicePrice: [
          { required: true, message: "服务价格不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "订单状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单管理列表 */
    getList() {
      this.loading = true;
      listOrders(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.ordersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderNumber: null,
        customerName: null,
        serviceContent: null,
        servicePrice: null,
        status: "待确定",
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.handleQuery();
    },
    // 订单状态字典翻译
    statusFormat(status) {
      const statusMap = {
        '待确定': '待确定',
        '进行中': '进行中',
        '待评价': '待评价',
        '已完成': '已完成',
        '退款/售后': '退款/售后'
      };
      return statusMap[status] || status;
    },
    // 订单状态标签类型
    statusTagType(status) {
      const statusMap = {
        '待确定': 'info',
        '进行中': 'primary',
        '待评价': 'warning',
        '已完成': 'success',
        '退款/售后': 'danger'
      };
      return statusMap[status] || '';
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 生成随机订单号
      const now = new Date();
      const timestamp = now.getTime().toString();
      const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
      this.form.orderNumber = 'BS' + timestamp.slice(-8) + randomNum;
      
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids[0];
      getOrders(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 查看详情操作 */
    handleView(row) {
      getOrders(row.orderId).then(response => {
        this.viewForm = response.data;
        this.viewDialogVisible = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrders(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 更多操作 */
    handleMoreActions(command, row) {
      if (command === 'complete') {
        this.$modal.confirm('是否确认将订单标记为完成？').then(() => {
          const data = { ...row, status: '已完成' };
          updateOrders(data).then(response => {
            this.getList();
            this.$modal.msgSuccess("操作成功");
          });
        }).catch(() => {});
      } else if (command === 'cancel') {
        this.$modal.confirm('是否确认取消该订单？').then(() => {
          const data = { ...row, status: '退款/售后' };
          updateOrders(data).then(response => {
            this.getList();
            this.$modal.msgSuccess("操作成功");
          });
        }).catch(() => {});
      } else if (command === 'delete') {
        this.handleDelete(row);
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`);
    }
  }
};
</script> 